<template>
  <div class="app-container">
    <el-form size="small" :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="关键词">
        <el-input v-model="searchForm.keyword" clearable placeholder="搜索" @keyup.enter.native="search"/>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.created_time"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00','23:59:59']"
          :picker-options="{
            shortcuts: [
              {
                text: '最近一周',
                onClick: (picker) => {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
                }
              },
              {
                text: '最近一个月',
                onClick: (picker) => {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
                }
              }]
          }"
        />
      </el-form-item>
      <el-form-item label="排序">
        <el-select v-model="searchForm.sort" placeholder="排序" clearable>
          <el-option label="默认" value=""/>
          <el-option label="销量从大到小" value="sales_num desc"/>
          <el-option label="销量从小到大" value="sales_num asc"/>
          <el-option label="库存从多到少" value="store_count desc"/>
          <el-option label="库存从小到大" value="store_count asc"/>
          <el-option label="浏览量从高到底" value="click_count desc"/>
          <el-option label="浏览量从低到高" value="click_count asc"/>
          <el-option label="价格从高到低" value="goods_price desc"/>
          <el-option label="价格从低到高" value="goods_price asc"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="success" @click="$router.push({path:'/goods/form'})">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="商品编号" width="95">
        <template v-slot:default="{scope,row}">
          {{ row.goods_id }}
        </template>
      </el-table-column>

      <el-table-column label="商品名称" width="200" align="left">
        <template v-slot:default="{scope,row}">
          {{ row.goods_name }}
        </template>
      </el-table-column>
      <el-table-column label="封面" width="60" align="center">
        <template v-slot:default="{scope,row}">
          <el-image v-if="row.goods_image" :src="row.goods_image" :preview-src-list="[row.goods_image]"/>
        </template>

      </el-table-column>
      <el-table-column label="轮播图" width="200" align="center">
        <template v-slot:default="{scope,row}">
          <el-image
            v-if="row.goods_image_list"
            :src="row.goods_image_list[0]"
            :preview-src-list="row.goods_image_list"
          />
        </template>
      </el-table-column>
      <el-table-column label="上下架" width="100" align="center">
        <template v-slot:default="{scope,row}">
          <el-switch
            v-model="row.is_on_sale"
            :active-value="1"
            :inactive-value="0"
            @change="changeStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="销售单价" width="150" align="center">
        <template v-slot:default="{scope,row}">
          {{ row.goods_price }}
        </template>
      </el-table-column>
      <el-table-column label="市场价" width="150" align="center">
        <template v-slot:default="{scope,row}">
          {{ row.market_price }}
        </template>
      </el-table-column>
      <el-table-column label="运费" width="150" align="center">
        <template v-slot:default="{scope,row}">
          {{ row.shipping_fee }}
        </template>
      </el-table-column>
      <el-table-column label="销量" width="150" align="center">
        <template v-slot:default="{scope,row}">
          {{ row.sales_num }}
        </template>
      </el-table-column>

      <el-table-column label="分类" width="100" align="center">
        <template v-slot:default="{scope,row}">
          {{ row.category_name }}
        </template>
      </el-table-column>
      <el-table-column label="库存" width="100" align="center">
        <template v-slot:default="{scope,row}">
          <span v-if="row.store_count<10" class="bs-red">{{ row.store_count }}</span>
          <span v-else class="bs-green">{{ row.store_count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="浏览量" width="100" align="center">
        <template v-slot:default="{scope,row}">
          <span v-if="row.click_count<10" class="bs-red">{{ row.click_count }}</span>
          <span v-else class="bs-green">{{ row.click_count }}</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" width="160" align="center">
        <template v-slot:default="{scope,row}">
          <span>{{ row.updated_at || '/' }}</span>
          <br>
          <span class="bs-green">{{ row.last_active_platform }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="操作" fixed="right" width="180">
        <template v-slot:default="{scope,row}">
          <el-row class="row-action-btns">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-view"
              title="预览"
              circle
              @click="previewGoods(row)"
            />
            <el-button
              size="mini"
              type="warning"
              title="库存管理"
              icon="el-icon-box"
              circle
              @click="$router.push({name:'goodsStockForm',query:{goods_id:row.goods_id, type:listQuery.type}})"
            />

            <el-button
              size="mini"
              type="primary"
              title="编辑"
              icon="el-icon-edit"
              circle
              @click="$router.push({path:'/goods/form',query:{goods_id:row.goods_id, type:listQuery.type}})"
            />
            <el-button
              v-if="listQuery.type!=='delete'"
              title="删除"
              size="mini"
              type="info"
              icon="el-icon-delete"
              circle
              @click="del(row.goods_id)"
            />
            <el-button
              v-if="listQuery.type==='delete'"
              title="还原"
              size="mini"
              type="info"
              icon="el-icon-refresh-left"
              circle
              @click="restore(row.goods_id)"
            />
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"
    />
    <preview
      :goods-preview-visible="goodsPreviewVisible"
      :goods-preview-url="goodsPreviewUrl"
      :width="375"
      @update:goodsPreviewVisible="goodsPreviewVisible = $event"
    ></preview>
  </div>

</template>

<script>
import api from '@/api/goods'
import Pagination from '@/components/Pagination'
import preview from '@/components/goods/preview.vue'
export default {
  components: {
    Pagination,preview
  },
  filters: {},
  props: {
    // 接收父组件传递的类型
    type: {
      type: String,
      default: 'onSale',
      validator(value) {
        return ['onSale', 'offSale', 'delete'].includes(value)
      }
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      searchForm: {
        keyword: '',
        category_id: '',
        sort: '',
        created_time: ''
      },
      goodsPreviewVisible: false,
      goodsPreviewUrl: ''
    }
  },
  computed: {
    listQuery() {
      return {
        type: this.type, // 根据prop动态设置type
        page: this.$route.query.page || 1,
        limit: this.$route.query.limit || 10,
        sort: this.$route.query.sort || ''
      }
    }
  },
  created() {
    if (this.$route.query.hasOwnProperty('goods_id')) {
      this.searchForm.keyword = this.$route.query.goods_id
      this.listQuery = Object.assign(this.listQuery, this.searchForm)
    }
    this.fetchData()
  },
  methods: {
    previewGoods(goods_info) {
      this.goodsPreviewUrl = `https://sku.alipay168.cn/#/pages/goods/detail?item_id=${goods_info.goods_id}`;
      this.goodsPreviewVisible = true;
    },
    handleCategorySelect(category) {
      this.searchForm.category_id = category
    },
    fetchData() {
      this.listLoading = true
      api.getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    restore(id) {
      this.$confirm('确定还原吗？', '还原商品到库存', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.restore({ goods_id: id }).then(response => {
          this.$message({
            type: 'success',
            message: '还原成功!'
          })
          this.fetchData()
        })
      })
    },
    del(id) {
      this.$confirm('此操作将商品移到回收站, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.del({ goods_id: id }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.fetchData()
        })
      }).catch(() => {

      })
    },
    search() {
      this.listQuery.page = 1
      Object.assign(this.listQuery, this.searchForm)
      this.fetchData()
    },
    changeStatus(row) {
      api.status({ goods_id: row.goods_id })
        .then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
        })
    }
  }

}
</script>

<style>
.el-image {
  width: 46px;
  height: 46px;
}

.bs-red {
  color: #ff0000;
}

.bs-green {
  color: #089c08;
}
</style>
